//
//  StepMakeIconViewController.m
//  IconMaster
//
//  Created by nhn on 1/4/15.
//  Copyright (c) 2015 为为. All rights reserved.
//
 
#import "StepMakeIconViewController.h"
#import "ImageLabelButton.h"
#import "UITabBarLikeButton.h"
#import "ImageGridTableViewController.h"
#import "DBOperation.h"
#import "CIconView.h"
#import "TextNoteLabel.h"
#import "TextViewController.h"
#import "AdAndHint.h"
#import "AppDelegate.h"
#import "KeepLayout.h"
#import "IconScrollerView.h"
#import "IconScrollerBarView.h"
@interface StepMakeIconViewController ()<IconScrollerViewDelegate, IconScrollerBarViewDelegate>
@property (nonatomic, strong) UIView* toolbarView;

@property (nonatomic, strong) IconScrollerBarView *iconScrollerBarView;

@property (nonatomic, strong) IconScrollerView *iconScrollerView;
@property (nonatomic, strong) CIconView* iconView;

@property (nonatomic, assign) BOOL textSpritePositionChanged;
@property (nonatomic, assign) CGPoint originTextSpriteCenter;

@property (nonatomic, strong) UIImage* originIconImage;
@property (nonatomic, strong) UIImage* originIconFrame;

@property (nonatomic, strong) SpriteContainerView* spriteContainer;
@property (nonatomic, strong) ImageGridTableViewController* lastSkinController;
@property (nonatomic, strong) ImageGridTableViewController* lastFrameController;
@property (nonatomic, strong) ImageGridTableViewController* lastDecoController;
@property (nonatomic, strong) TextViewController* lastTextController;

@property (nonatomic, strong) NSDictionary *resultDict;
@end

@implementation StepMakeIconViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    self.navigationItem.rightBarButtonItem.title = @"next";
	self.title = @"制作图标";
    
    UIBarButtonItem *barItenBu = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(popToFontVC)];
    self.navigationItem.rightBarButtonItem = barItenBu;
    [self setImageViewINNav];
    
    self.originIconImage = self.font_image;
    [self creatIconScrollerBarView];
//    [self createToolBar];
    if (self.resultDictFont) {
        [self resetIconView:self.resultDictFont[@"iconView"]];
    }else{
    
        [self resetIconView:nil];
    }
    
   
//    self.navigationController.navigationBar.hidden =YES;
	
    
    [self initSpriteContainerView];
//     [self.iconView setBackgroundImage:self.originIconImage];
}
- (void)popToFontVC{

//    StepBaseViewController* curController = (StepBaseViewController*)[self currentController];
////    StepBaseViewController* nextController = (StepBaseViewController*)[self nextController];
//    
//    if (curController) {
//        if (![curController canMoveToNextController]) {
//            return;
//        }
//        
////        [self.resultDict addEntriesFromDictionary:[curController produceOutput]];
//    }
    
//    [self showNextStep];
//    
//    if (nextController) {
//        [nextController processInput:self.resultDict];
//    }
     
    self.resultDict  = [self produceOutput];
     
    if (self.returnValueBlock) {
        self.returnValueBlock(self.resultDict);
    }
    [self.navigationController popViewControllerAnimated:YES];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IconScrollerBarView

- (void)creatIconScrollerBarView{
    int grpid = [[[DBOperation skinGroupArray][0] objectForKey:GROUP_KEY_ID] intValue];
    NSArray *imageCount = [DBOperation imageArrayForGroupID:grpid];
    if (self.iconScrollerBarView) {
        return;
    }
    self.iconScrollerBarView = [[IconScrollerBarView alloc] init];
    self.iconScrollerBarView.deleagte = self;
    self.iconScrollerBarView.frame = CGRectMake(0, KHeight- 150, KWidth, 150);
    [self.iconScrollerBarView creatSeledImgBackGroundView];
    self.iconScrollerBarView.backgroundColor =Color(53, 194, 203);
    [self.view addSubview:self.iconScrollerBarView];
//    self.iconScrollerBarView.sd_layout.leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0).heightIs(150);
}

- (void)buttonClickWithFourSeleted:(NSInteger)index{
//       self.iconScrollerBarView.sd_layout.leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0).heightIs(230);
//    [self.iconScrollerBarView setFrame:CGRectMake(0, KHeight - 230, KWidth, 230)];
//    self.iconScrollerBarView.frame = CGRectMake(0, KHeight - 230, KWidth, 230);
//    [self.view layoutIfNeeded];
//    [self.iconScrollerBarView  setNeedsDisplayInRect:CGRectMake(0, KHeight - 230, KWidth, 230)];
    [self.iconScrollerBarView setHeight:230];
//    
//    [self.iconScrollerBarView removeFromSuperview];
    switch (index) {
        case 0:
            //背景
            [self backgroundDB];
            break;
        case 1:
            //边框
            [self frameDB];
            break;
        case 2:
            //装饰
            [self decoDB];
            break;
        case 3:
            //文字
             
            [self textButtonPressed:nil];
            break;
        default:
            break;
    }
    
//    int grpid = [[[DBOperation skinGroupArray][0] objectForKey:GROUP_KEY_ID] intValue];
//    NSArray *imageCount = [DBOperation imageArrayForGroupID:grpid];
//    
//    //    NSLog(@"1 =%@ \n", [DBOperation imageArrayForGroupID:(int)[DBOperation skinGroupArray][0][@"GroupID"]]);
//    [self creatIconScrollerView:imageCount];
//    [self.iconScrollerBarView creatSeledImgBackGroundView:imageCount];

}

- (void)backgroundDB{
    
        int grpid = [[[DBOperation skinGroupArray][0] objectForKey:GROUP_KEY_ID] intValue];
        NSArray *imageCount = [DBOperation imageArrayForGroupID:grpid];
        [self.iconScrollerBarView dealWithImgArr:imageCount];
}
- (void)frameDB{

        int grpid = [[[DBOperation frameGroupArray][0] objectForKey:GROUP_KEY_ID] intValue];
        NSArray *imageCount = [DBOperation imageArrayForGroupID:grpid];
        [self.iconScrollerBarView dealWithImgArr:imageCount];
}
- (void)decoDB{

    int grpid = [[[DBOperation decoGroupArray][0] objectForKey:GROUP_KEY_ID] intValue];
    NSArray *imageCount = [DBOperation imageArrayForGroupID:grpid];
    [self.iconScrollerBarView dealWithImgArr:imageCount];

}
- (void)okbuttonAction:(UIImage *)image{

//    [self.iconView setBackgroundImage:image];
    self.resultDict  = [self produceOutput];
    
    if (self.returnValueBlock) {
        self.returnValueBlock(self.resultDict);
    }
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)buttonMoreWithBar:(NSInteger)index{

    switch (index) {
        case 0:
            //背景
            [self skinButtonPressed:nil];
            break;
        case 1:
            //边框
            
            [self frameButtonPressed:nil];
            break;
        case 2:
            //装饰
            [self decoButtonPressed:nil];
            break;
        case 3:
            //文字
            
            [self textButtonPressed:nil];
            break;
        default:
            break;
    }

}

- (void)buttonSelected:(UIImage *)image andTypeIndex:(NSInteger)index{

    switch (index) {
        case 0:
            [self.iconView setBackgroundImage:image];
            break;
        case 1:
            [self.iconView setFrameImage:image];
            break;
        case 2:
            [self addSpriteWithImage:image];
            break;
        case 3:
//            [self tetController];
            [self textButtonPressed:nil];
            break;
            
        default:
            break;
    }
     
}

#pragma mark - toolbar

- (void)createToolBar {
	if (self.toolbarView) {
		return;
	}
	
	self.toolbarView = [[UIView alloc] init];
	[self.view addSubview:self.toolbarView];

	self.toolbarView.keepLeftInset.equal = 0;
	self.toolbarView.keepRightInset.equal = 0;
	self.toolbarView.keepBottomInset.equal = 0;
	self.toolbarView.keepHeight.equal = 52+999i;
//	self.toolbarView.backgroundColor = [[UINavigationBar appearance] barTintColor];
	
	CGSize buttonSize = CGSizeMake(50, 42);
	
	UIColor* tintColor = [UIColor whiteColor];
	UIImage* image = [CImageUtil imageFromImage:nil orName:@"sqare_button.png" withTintColor:tintColor];
	UIButton* skinButton = [self createToolbarButtonWithImage:image title:LOC(@"skin")];
	[self.toolbarView addSubview:skinButton];
	skinButton.keepHorizontalCenter.equal = 1.0/4.0*0.5;
    [self.toolbarView addConstraint:[NSLayoutConstraint constraintWithItem:skinButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.toolbarView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:2]];
	[skinButton keepSize:buttonSize];
    [skinButton addTarget:self action:@selector(skinButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	
	image = [CImageUtil imageFromImage:nil orName:@"round_frame_button.png" withTintColor:tintColor];
	UIButton* frameButton = [self createToolbarButtonWithImage:image title:LOC(@"frame")];
	[self.toolbarView addSubview:frameButton];
	frameButton.keepHorizontalCenter.equal = 1.0/4.0*1.5;
    [self.toolbarView addConstraint:[NSLayoutConstraint constraintWithItem:frameButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.toolbarView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:2]];
	[frameButton keepSize:buttonSize];
    [frameButton addTarget:self action:@selector(frameButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	
	image = [CImageUtil imageFromImage:nil orName:@"heart_button.png" withTintColor:tintColor];
	UIButton* decoButton = [self createToolbarButtonWithImage:image title:LOC(@"decor")];
	[self.toolbarView addSubview:decoButton];
	decoButton.keepHorizontalCenter.equal = 1.0/4.0*2.5;
    [self.toolbarView addConstraint:[NSLayoutConstraint constraintWithItem:decoButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.toolbarView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:2]];
	[decoButton keepSize:buttonSize];
    [decoButton addTarget:self action:@selector(decoButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	
	image = [CImageUtil imageFromImage:nil orName:@"text_button.png" withTintColor:tintColor];
	UIButton* textButton = [self createToolbarButtonWithImage:image title:LOC(@"text")];
	[self.toolbarView addSubview:textButton];
	textButton.keepHorizontalCenter.equal = 1.0/4.0*3.5;
    [self.toolbarView addConstraint:[NSLayoutConstraint constraintWithItem:textButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.toolbarView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:2]];
	[textButton keepSize:buttonSize];
    [textButton addTarget:self action:@selector(textButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
}

- (UIButton*)createToolbarButtonWithImage:(UIImage*)image title:(NSString*)title {
    UIColor* highlightColor = [UIColor yellowColor];
	UITabBarLikeButton* button = [UITabBarLikeButton buttonWithType:UIButtonTypeCustom];
    
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:[CImageUtil imageFromImage:image orName:nil withTintColor:highlightColor] forState:UIControlStateHighlighted];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:highlightColor forState:UIControlStateHighlighted];
    button.titleLabel.adjustsFontSizeToFitWidth = YES;
    button.titleLabel.font = [button.titleLabel.font fontWithSize:13];
    button.spaceBetweenImageAndLabel = 3;
    
	return button;
}

#pragma mark - action

- (void)skinButtonPressed:(id)sender {
    
    if (self.spriteContainer) {
        [self.spriteContainer unselectAllSprite];
    }
    
    if (!self.lastSkinController) {
        ImageGridTableViewController* controller = nil;
        controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation skinGroupArray]];
        controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex, UIImage* image) {
            [self.iconView setBackgroundImage:image];
            [self dismissViewControllerAnimated:YES completion:nil];
        };
        
        controller.cancelPressedBlock = ^(ImageGridTableViewController* ctl) {
            [ctl dismissViewControllerAnimated:YES completion:nil];
        };
        controller.resetPressedBlock = ^(ImageGridTableViewController* ctl) {
            [self resetIconBackGroundImage];
            [ctl dismissViewControllerAnimated:YES completion:nil];
        };
        self.lastSkinController = controller;
    }
    
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:self.lastSkinController]
                       animated:YES
                     completion:^{
                         [self showAdmobInController:self.lastSkinController];
                     }];

}

- (void)frameButtonPressed:(id)sender {
    if (self.spriteContainer) {
        [self.spriteContainer unselectAllSprite];
    }
    
    if (!self.lastFrameController) {
        ImageGridTableViewController* controller = nil;
        controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation frameGroupArray]];
        
        controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex, UIImage* image) {
            [self.iconView setFrameImage:image];
            [self dismissViewControllerAnimated:YES completion:nil];
        };
        
        controller.cancelPressedBlock = ^(ImageGridTableViewController* ctl) {
            [ctl dismissViewControllerAnimated:YES completion:nil];
        };
        controller.resetPressedBlock = ^(ImageGridTableViewController* ctl) {
            [self resetIconFrame];
            [ctl dismissViewControllerAnimated:YES completion:nil];
        };
        self.lastFrameController = controller;
    }
    
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:self.lastFrameController]
					   animated:YES
					 completion:^{
						 [self showAdmobInController:self.lastFrameController];
					 }];
}

- (void)decoButtonPressed:(id)sender {
    if (self.spriteContainer) {
        [self.spriteContainer unselectAllSprite];
    }
    
    if (!self.lastDecoController) {
        ImageGridTableViewController* controller = nil;
        controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation decoGroupArray]];
        controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex, UIImage* image) {
            int iid = [DBOperation getIDFromImage:image];
            if (iid != DEFAULT_ICON_ID.integerValue) {
                [self addSpriteWithImage:image];
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        };
        
        controller.cancelPressedBlock = ^(ImageGridTableViewController* ctl) {
            [ctl dismissViewControllerAnimated:YES completion:nil];
        };
        controller.resetPressedBlock = ^(ImageGridTableViewController* ctl) {
            [ctl dismissViewControllerAnimated:YES completion:nil];
        };
        controller.hideRightBarButtonItem = YES;
        self.lastDecoController = controller;
    }
    
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:self.lastDecoController]
					   animated:YES
					 completion:^{
						 [self showAdmobInController:self.lastDecoController];
					 }];
}

- (void)textButtonPressed:(id)sender {
//     [self.iconScrollerBarView setHeight:150];
    self.iconScrollerBarView.frame = CGRectMake(0, KHeight- 150, KWidth, 150);
    [self.iconScrollerBarView.iconScrollerView removeFromSuperview];
    if (self.lastTextController.textNoteSprite.isEditting) {
        [self enableKeyboardNotification];
        UIControl* backgroundControl = [[UIControl alloc] initWithFrame:self.view.bounds];
        backgroundControl.backgroundColor = [UIColor clearColor];
        backgroundControl.frame = self.view.bounds;
        backgroundControl.tag = 0xbc;
        [backgroundControl addTarget:self action:@selector(textControllerBackgroundTapped:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:backgroundControl];
        
        [self.view addSubview:self.lastTextController.view];
        [self.lastTextController.view setFrame:CGRectMake(0, self.view.bounds.size.height-self.lastTextController.view.frame.size.height, self.view.bounds.size.width, self.lastTextController.view.frame.size.height)];

        [self.lastTextController textButtonPressed:self.lastTextController.textNoteSprite];
    } else {
        if (self.spriteContainer) {
            [self.spriteContainer unselectAllSprite];
        }
        [self tetController];
    }
    
   }

- (void)tetController{

    TextViewController* controller = [self ensureTextViewController];
    
    [self enableKeyboardNotification];
    
    UIControl* backgroundControl = [[UIControl alloc] initWithFrame:self.view.bounds];
    backgroundControl.backgroundColor = [UIColor clearColor];
    backgroundControl.frame = self.view.bounds;
    backgroundControl.tag = 0xbc;
    [backgroundControl addTarget:self action:@selector(textControllerBackgroundTapped:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:backgroundControl];
    
    [self.view addSubview:controller.view];
    [controller.view setFrame:CGRectMake(0, self.view.bounds.size.height-controller.view.frame.size.height, self.view.bounds.size.width, controller.view.frame.size.height)];
    [controller textButtonPressed:nil];

}
#pragma mark - icon view

- (void)resetIconView:(CIconView*)iconView {
	if (self.iconView && !iconView) {
		return;
	}
	
    if (self.iconView) {
        [self.iconView removeFromSuperview];
    }
    
    CGSize size = CGSizeMake(114, 114);
    if (!iconView) {
        iconView = [CIconView iconViewFromNibWithCornorRadius];
    }
    self.iconView = iconView;
    
    iconView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:iconView];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:iconView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:iconView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-20]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:iconView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:size.width]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:iconView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:size.height]];
    
    if (![self.iconView getBackgroundImage]) {
//        [self.iconView setBackgroundImageWithName:@"default_icon.png"];
        [self resetIconBackGroundImage];
    }
    
    self.originIconImage = [self.iconView getBackgroundImage];
    self.originIconFrame = [self.iconView getFrameImage];
    
    __weak typeof(self) bself = self;
	self.iconView.spriteContainer.spriteSelected = ^(SpriteContainerView* container, SpriteView* sprite) {
		[bself moveSpriteFromIconView:sprite];
	};
	
	[self.view bringSubviewToFront:self.spriteContainer];
}

- (void)resetIconBackGroundImage {
    [self.iconView setBackgroundImage:self.originIconImage];
}

- (void)resetIconFrame {
    [self.iconView setFrameImage:self.originIconFrame];
}

- (void)setIconViewBackgroundImage:(UIImage*)image {
	self.originIconImage = image;
	[self.iconView setBackgroundImage:image];
}

#pragma mark - sprite view

- (void)initSpriteContainerView
{
    if (self.spriteContainer) {
        [self.spriteContainer removeFromSuperview];
    }
    
    self.spriteContainer = [[SpriteContainerView alloc] init];
    self.spriteContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.spriteContainer];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[sc]-0-|" options:0 metrics:nil views:@{@"sc":self.spriteContainer}]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[sc]-0-[tabbar]" options:0 metrics:nil views:@{@"sc":self.spriteContainer, @"tabbar":self.iconScrollerBarView}]];
    
	__block typeof(self) bself = self;
	[self.view bringSubviewToFront:self.spriteContainer];
    
	self.spriteContainer.hidden = true;
	self.spriteContainer.spriteSelected = ^(SpriteContainerView* spc, SpriteView* sprite) {
		
	};
	self.spriteContainer.spriteUnselected = ^(SpriteContainerView* spc, SpriteView* sprite) {
		[bself moveSpriteToIconView:sprite];
	};
	self.spriteContainer.spriteDelete = ^(SpriteContainerView* spc, SpriteView* sprite) {
		[bself updateSpriteContainerVisibility];
	};
	self.spriteContainer.shouldUnselectSprite = ^(SpriteContainerView* spc, SpriteView* sprite){
		return [bself shouldUnselectSprite:sprite];
	};
}

- (void)addSpriteWithImage:(UIImage*)image {
    [self.iconView addSpriteWithImage:image];
}

- (void)moveSpriteToIconView:(SpriteView*)sprite
{
	ChangeViewsSuperView(sprite, self.iconView.spriteContainer);
    [self removeEmptyTextSprite:sprite];
	self.spriteContainer.hidden = true;
	
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
	if (textNote) {
		[textNote hideKeyboard];
        
        TextViewController* controller = self.lastTextController;
		controller.textNoteSprite = nil;
	}
}

- (void)moveSpriteFromIconView:(SpriteView*)sprite
{
	self.spriteContainer.hidden = false;
	ChangeViewsSuperView(sprite, self.spriteContainer);
	
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
    if (textNote) {
        TextViewController* controller = [self ensureTextViewController];
        controller.textNoteSprite = sprite;
    }
}

- (void)updateSpriteContainerVisibility
{
	if ([[self.spriteContainer subviews] count]) {
		self.spriteContainer.hidden = false;
	} else {
		self.spriteContainer.hidden = true;
	}
}

- (void)removeEmptyTextSprite:(SpriteView*)sprite {
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
	if (textNote) {
		if (!textNote.text || [textNote.text isEqualToString:@""]) {
			[sprite removeFromSuperview];
		}
	}
    
    [self updateSpriteContainerVisibility];
}

- (BOOL)shouldUnselectSprite:(SpriteView*)sprite
{
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
	if (textNote) {
		if ([textNote isKeyboardShown]) {
			[textNote hideKeyboard];
			return false;
		}
	}
	return true;
}

- (TextNoteLabel*)getTextNoteFromSprite:(SpriteView*)sprite
{
	TextNoteLabel* textLabel = nil;
    textLabel = (TextNoteLabel*)[sprite getViewWithClass:[TextNoteLabel class]];
    
	return textLabel;
}

- (TextViewController*)ensureTextViewController
{
    if (!self.lastTextController) {
        __block typeof(self) bself = self;
        TextViewController* controller = [[TextViewController alloc] init];
        controller.textFieldPressedBlock = ^(TextViewController* tvc) {
            [bself addTextNodeSpriteIfNeed];
        };
        self.lastTextController = controller;
    }
    
    return self.lastTextController;
}

- (void)addTextNodeSpriteIfNeed
{
    TextViewController* textController = self.lastTextController;
	if (!textController.textNoteSprite) {
		TextNoteLabel* textLabel = [[TextNoteLabel alloc] initWithFrame:CGRectMake(0, 0, 114, 114)];
		SpriteView* sprite = [[SpriteView alloc] init];
		[sprite setView:textLabel];
		[self.iconView addSprite:sprite];
        textController.textNoteSprite = sprite;
	}
}

- (void)hideTextControllerIfNeed {
	UIView* backView = [self.view viewWithTag:0xbc];
	if (backView) {
		[self textControllerBackgroundTapped:backView];
	}
}

- (void)textControllerBackgroundTapped:(id)sender
{
    UIControl* control = (UIControl*)sender;
    [control removeFromSuperview];
	
    TextViewController* controller = self.lastTextController;
	if (controller) {
		[controller hideKeyboard];
		
		[UIView animateWithDuration:0.4
						 animations:^{
							 CGRect frame = controller.view.frame;
							 frame.origin.y = self.view.bounds.size.height;
							 controller.view.frame = frame;
						 }
						 completion:^(BOOL finished) {
							 [controller.view removeFromSuperview];
						 }
		 ];
        
        if (controller.textNoteSprite) {
            [self removeEmptyTextSprite:controller.textNoteSprite];
        }
	}
    
    if (self.textSpritePositionChanged && self.lastTextController && self.lastTextController.textNoteSprite) {
        self.textSpritePositionChanged = NO;
        
        [UIView animateWithDuration:0.4
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             if (CGPointEqualToPoint(self.originTextSpriteCenter, CGPointZero)) {
                                 self.lastTextController.textNoteSprite.center = self.iconView.center;
                             } else {
                                 self.lastTextController.textNoteSprite.center = self.originTextSpriteCenter;
                             }
                         }
                         completion:^(BOOL finished) {
                             
                         }];
    }
    
    [self disableKeyboardNotification];
}

#pragma mark - keyboard

- (void)enableKeyboardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)disableKeyboardNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShowNotification:(NSNotification*)notification {
    CGRect endFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    SpriteView* spriteView = self.lastTextController.textNoteSprite;
    CGPoint textSpriteBottom = [spriteView.superview convertPoint:spriteView.center toView:nil];
    textSpriteBottom.y += spriteView.frame.size.height/2;
	
	CGFloat offset = endFrame.origin.y-(self.lastTextController.view.frame.size.height-endFrame.size.height)-textSpriteBottom.y;
    
    if (offset < 0 && self.lastTextController && self.lastTextController.textNoteSprite) {
        self.textSpritePositionChanged = YES;
        self.originTextSpriteCenter = self.lastTextController.textNoteSprite.center;
		
        [UIView animateWithDuration:0.4
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             CGPoint center = self.lastTextController.textNoteSprite.center;
                             self.lastTextController.textNoteSprite.center = CGPointMake(center.x, center.y+offset+16);
                         }
                         completion:^(BOOL finished) {
                             
                         }];
    }
}

- (void)keyboardWillHideNotification:(NSNotification*)notification {
//    CGRect endFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
//    if (self.textSpritePositionChanged && self.lastTextController && self.lastTextController.textNoteSprite) {
//        self.textSpritePositionChanged = NO;
//        
//        [UIView animateWithDuration:0.4
//                              delay:0.0
//                            options:UIViewAnimationOptionCurveEaseOut
//                         animations:^{
//                             if (CGPointEqualToPoint(self.originTextSpriteCenter, CGPointZero)) {
//                                 self.lastTextController.textNoteSprite.center = self.iconView.center;
//                             } else {
//                                 self.lastTextController.textNoteSprite.center = self.originTextSpriteCenter;
//                             }
//                         }
//                         completion:^(BOOL finished) {
//                             
//                         }];
//    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - StepBaseViewController 

- (void)processInput:(NSDictionary *)infoDict {
    
}

- (NSDictionary *)produceOutput {
    [self.spriteContainer unselectAllSprite];
	[self hideTextControllerIfNeed];
    UIImage* iconImage = [self.iconView iconImage];
    return @{@"iconImage":iconImage, @"iconView":self.iconView};
}

#pragma mark - admob

- (void)showAdmobInController:(UIViewController*)controller {
	[AdAndHint showInterstitialViewInController:controller
							   withRatioPercent:40];
}

#pragma mark -- ScrollerICONView

- (void)creatIconScrollerView:(NSArray *)arr{
    [self.iconScrollerView removeFromSuperview];
    self.iconScrollerView = [[IconScrollerView alloc] initWithFrame:CGRectMake(0, KHeight - 120, KWidth, 60)];
    self.iconScrollerView.contentArr = arr;
    [self.iconScrollerView initSubViewsInArr];
    self.iconScrollerView.backgroundColor = [UIColor grayColor];
    self.iconScrollerView.delegate = self;
    [self.view addSubview:self.iconScrollerView];
//    self.iconScrollerView.sd_layout.leftSpaceToView(self, 0).rightSpaceToView(self, 0).bottomSpaceToView(self.toolbarView, 10).heightIs(60);
}
- (void)butonMore{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"选择背景后会覆盖原来的您的图片，您要继续吗" preferredStyle:UIAlertControllerStyleAlert];
        __weak typeof(alert) weakAlert = alert;
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            if (self.spriteContainer) {
                [self.spriteContainer unselectAllSprite];
            }
            
            if (!self.lastSkinController) {
                ImageGridTableViewController* controller = nil;
                controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation skinGroupArray]];
                controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex, UIImage* image) {
                    [self.iconView setBackgroundImage:image];
                    [self dismissViewControllerAnimated:YES completion:nil];
                };
                
                controller.cancelPressedBlock = ^(ImageGridTableViewController* ctl) {
                    [ctl dismissViewControllerAnimated:YES completion:nil];
                };
                controller.resetPressedBlock = ^(ImageGridTableViewController* ctl) {
                    [self resetIconBackGroundImage];
                    [ctl dismissViewControllerAnimated:YES completion:nil];
                };
                self.lastSkinController = controller;
            }
            
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:self.lastSkinController]
                               animated:YES
                             completion:^{
                                 [self showAdmobInController:self.lastSkinController];
                             }];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    //        NSLog(@"点击了取消按钮");
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];


}
- (void)buttonImage:(UIImage *)image{
     [self.iconView setBackgroundImage:image];
//    self.originIconImage = image;
    
}
@end
